import { Component, OnInit } from '@angular/core';
import { ActivatedRoute } from '@angular/router';
import { FormGroup, FormBuilder, Validators } from '@angular/forms';
import { NzMessageService } from 'ng-zorro-antd';
import { NzNotificationService } from 'ng-zorro-antd';

import { UsermanegeService, User, Role } from '../../../DM/usermanege.service';
@Component({
  selector: 'app-user-editor',
  templateUrl: './user-editor.component.html',
  styleUrls: ['./user-editor.component.css']
})
export class UserEditorComponent implements OnInit {

  _user: User = new User;
  _changeUserDataForm: FormGroup;
  _isLoading: boolean;
  _roleLs: Role[] = [];

  constructor(
    private usermanegeService: UsermanegeService,
    private activatedRoute: ActivatedRoute,
    private fb: FormBuilder,
    private msgService: NzMessageService,
    private noticeService: NzNotificationService,
  ) {
    this._changeUserDataForm = fb.group({
      "username": ["", [Validators.required]],
      "role": ["", [Validators.required]],
    });
  }

  async ngOnInit() {
    this._roleLs = await this.usermanegeService.getRoleLs();
    this.activatedRoute.params.subscribe(async (route: { id }) => {
      this._user = await this.usermanegeService.getUserById(route.id);
      this._changeUserDataForm.controls["username"].setValue(this._user.UserName);
    });
  }

  async _submitForm() {
    try {
      for (let key in this._changeUserDataForm.controls) {
        this._changeUserDataForm.controls[key].markAsDirty();
      }
      if (this._changeUserDataForm.valid) {
        this._isLoading = true;
        await this.usermanegeService.updateUser(
          this._user.UserId,
          this._changeUserDataForm.controls.username.value,
          this._changeUserDataForm.controls.role.value,
        );
        this._isLoading = false;
        this.msgService.success('变更成功');
        this.noticeService.blank('资料变更', `您刚刚为用户${this._user.UserName}变更了用户资料`);
        this._changeUserDataForm.reset();
        await this.ngOnInit();
      }
    } catch (err) {
      console.error(err);
      this.msgService.error('变更失败');
      this.noticeService.blank('资料变更', `由于${err}，变更资料操作失败`);
    }
  }

}
